//
//  YZGListDataManager.m
//  sisitv_ios
//
//  Created by apple on 17/2/27.
//  Copyright © 2017年 JLXX--YZG. All rights reserved.
//

#import "YZGListDataManager.h"
#import "YZGRequest.h"

@interface YZGListDataManager ()

//limit_begin：从第几条开始取(默认从第0条开始取)
@property (nonatomic , copy) NSString *limit_begin;

//limit_num：需要取几条(默认取20条)
@property (nonatomic , copy) NSString *limit_num;

@end

@implementation YZGListDataManager

-(instancetype)initWithDelegate:(id<YZGListDataManagerDelegate>)delegate{
    if (self = [super init]) {
        self.delegate = delegate;
        self.limit_num = @"20";
        self.responseObject = [NSMutableArray array];
    }
    return self;
}

-(void)pullDownToRefresh{
    self.limit_begin = @"0";
    self.isRefresh = YES;
    [self loadData];
}

-(void)pullUpToLoadMore{
    int limit_begin = self.limit_begin.intValue;
    limit_begin = limit_begin + self.limit_num.intValue;
    self.limit_begin= [NSString stringWithFormat:@"%d",limit_begin];
    self.isRefresh = NO;
    [self loadData];
}

-(void)loadData{
    self.networkError = NO;
    [self.responseObject removeAllObjects];
    
    [self startNetRequest];
}

-(void)startNetRequest{
    
    [self.netRequest cheeckRequestParams];
    
    NSMutableDictionary *listRequestParam = [self.netRequest.requestParam mutableCopy];
    [listRequestParam setObject:self.limit_begin forKey:@"limit_begin"];
    self.netRequest.requestParam = listRequestParam.copy;
    
    __weak typeof(self) weakSelf = self;
    [self.netRequest startWithCompletionBlockWithSuccess:^(__kindof YZGRequest * _Nonnull request) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf handleServerData:request.responseObject];
    } failure:^(__kindof YZGRequest * _Nonnull request) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf handleError:request];
    }];
}

-(void)handleServerData:(NSDictionary *)responseObject{
    
    [self parseServerData:responseObject];
    
    NSInteger limit_end = [responseObject[@"limit_end"] integerValue];
    self.isNeedLoadMore = limit_end >= self.limit_num.intValue;
    
    if (self.isRefresh) {

        [self.delegate refreshNewSuccess:self];
        
    }else {
        [self.delegate loadMoreSuccess:self];
    }
    
    [self.delegate requestFinishedSuccess:self];
}
-(void)handleError:(YZGRequest *)request{
    
    self.networkError = request.isNetworkError;
    
    [self.delegate requestFinishedFaile:self];
}

-(void)parseServerData:(NSDictionary *)responseObject{
    NSAssert(NO, @"You Must implement This Mehtod ---%@---- %@",NSStringFromClass([self class]),NSStringFromSelector(_cmd));
}

@end
